package com.situ.springboot.controller;

import com.situ.springboot.util.JSONResult;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
@RequestMapping("/upload")
public class UploadController {

    // SpringMVC把前台上传的文件信息封装到MultipartFile
    @RequestMapping("/uploadImage")
    @ResponseBody
    public JSONResult uploadImage(MultipartFile file) {
        String name = UUID.randomUUID().toString().replace("-", "");
        // 4119bc9e4f4f4f3095f674fb81a0077b
        String fileName = file.getOriginalFilename();
        System.out.println(fileName);// 1.jpg
        String extension = FilenameUtils.getExtension(fileName);// jpg
        // 4119bc9e4f4f4f3095f674fb81a0077b.jpg
        String newFileName = name + "." +  extension;
        String filePath = "D:\\mypic\\" + newFileName;

        try {
            file.transferTo(new File(filePath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return JSONResult.ok("上传成功", newFileName);
    }

    public static void main(String[] args) {
        String uuid = UUID.randomUUID().toString();
        // b79d7713-33e1-42ac-acd0-8c6b1ffa8b05
        System.out.println(uuid);
        // 4119bc9e4f4f4f3095f674fb81a0077b
        System.out.println(uuid.replace("-",""));
    }
}
